package org.example;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class 任务槽共享组 {

    public static void main(String[] args) throws Exception {

        任务槽共享组 任务槽共享组 = new 任务槽共享组();

        Configuration configuration = new Configuration();
        configuration.setString("rest.port", "8088");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironment(configuration);


        env.setParallelism(1);


        DataStreamSource<String> localhost = env.socketTextStream("hadoop102", 8777);

        ParameterTool parameterTool = ParameterTool.fromArgs(args);

        // 讲每一行数据拆分
        SingleOutputStreamOperator<Tuple2<String, Integer>> returns = localhost
                .flatMap((String line, Collector<String> out) -> {
                    String[] words = line.split(" ");
                    for (String s : words) {
                        out.collect(s);
                    }
                })
                .returns(Types.STRING)
                .map(value -> Tuple2.of(value, 1)).slotSharingGroup("aaa")
                .returns(Types.TUPLE(Types.STRING, Types.INT));

        // 按照word进行分组
        KeyedStream<Tuple2<String, Integer>, Object> keyBy = returns.keyBy(value -> {
            return value.f0;
        });

        // 分组内进行聚合统计
        SingleOutputStreamOperator<Tuple2<String, Integer>> sum = keyBy.sum(1);
        sum.print();

        env.execute();
    }
}

